package app.fugema.shop.main.order.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;

import com.base.common.app.LoginUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.VerifyUtils;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.util.ArrayList;
import java.util.List;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.constants.PublicGlobal;
import app.fugema.shop.databinding.AddressAddAcBinding;
import app.fugema.shop.main.home.model.PoiPlaceBean;
import app.fugema.shop.main.online.view.SearchAddressActivity;
import app.fugema.shop.main.order.model.AddressDetailResult;
import app.fugema.shop.main.order.model.AddressNewEntity;
import app.fugema.shop.main.order.model.AddressResult;
import app.fugema.shop.main.home.vm.AddressVM;
import app.fugema.shop.main.setting.model.CustomRegionBean;
import app.fugema.shop.util.CityDataUtil;

public class AddressAddActivity extends BaseTitleActivity<AddressAddAcBinding, AddressVM> {

    private String userKey;
    /**
     * 添加地址入口
     *
     * @param context
     */
    public static void start(Context context)
    {
        Intent starter = new Intent(context, AddressAddActivity.class);
        starter.putExtra("isUpdate", false);
        context.startActivity(starter);
    }

    /**
     * 编辑入口
     *
     * @param context
     * @param adressId
     */
    public static void start(Context context, int adressId)
    {
        if (adressId == 0) return;
        Intent starter = new Intent(context, AddressAddActivity.class);
        starter.putExtra("isUpdate", true);
        //JacksonUtils.transBean2Json(adressAddInfo)
        starter.putExtra("adressAddInfo",adressId );
        context.startActivity(starter);
    }


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.address_add_ac);
    }

    //原来的地址选择器
    //private CityPickerView mPicker;

    private AddressNewEntity addressEntity;
    private boolean isUpdate = false;//是否编辑

    private int editAddressId;

    // 省市区 3 级联动
    private OptionsPickerView pickerView;

    private List<CustomRegionBean> province1Item = new ArrayList<>();
    private ArrayList<ArrayList<CustomRegionBean>> city2Item = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<CustomRegionBean>>> district3Item = new ArrayList<>();

    //private TencentLocationManager tlLocationMgr;

    private int mRegionId;

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("新建收货地址",R.color.white);

        userKey = LoginUtils.getToken();
        isUpdate = getIntent().getBooleanExtra("isUpdate", false);
        VerifyUtils.onTextChangedPhone(binding.etPhoneNO);
        if (isUpdate)
        {
            setTitle("编辑收货地址",R.color.white);
            //JacksonUtils.getJsonBean(getIntent().getStringExtra("adressAddInfo"), RefundProcessDetailResult.class);
            editAddressId = getIntent().getIntExtra("adressAddInfo",0);
            if (editAddressId != 0)
            {
                //先查询地址信息
                queryAddressId(editAddressId);

                binding.tvDefault.setOnClickListener(new OnClickCheckedUtil() {
                    @Override
                    public void onClicked(View view) {
                        viewModel.setDefAddr(editAddressId , userKey)
                                  .observe(getActivity(), new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity())
                                  {
                                      @Override
                                      protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                                      {
                                          UIUtils.showToastSafes("默认地址设置成功");
                                          binding.tvDefault.setVisibility(View.GONE);
                                      }
                        });
                    }
                });

                //binding.setItem(addressEntity);
            }

        } else {
            addressEntity = new AddressNewEntity();
            binding.tvDefault.setVisibility(View.GONE);
            if (PublicGlobal.getUserInfo() != null)
            {
                addressEntity.setShipTo(PublicGlobal.getUserInfo().getRealName());
                addressEntity.setPhone(PublicGlobal.getUserInfo().getCellPhone());
            }
            binding.setItem(addressEntity);
        }
        //mPicker = new CityPickerView();
        //mPicker.init(this);
        // 选择 地址
        binding.btnArea.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {

                //显示省市区
                pickerView.show();

                /*
                CityConfig cityConfig = new CityConfig.Builder().build();
                if (addressEntity == null || UIUtils.isEmpty(addressEntity.getRegionId()))
                {
                    cityConfig.setDefaultProvinceName("湖北省");
                    cityConfig.setDefaultCityName("武汉市");
                    cityConfig.setDefaultDistrict("洪山区");
                }
                else
                {
                    cityConfig.setDefaultProvinceName("湖北省");
                    cityConfig.setDefaultCityName("襄阳市");
                    cityConfig.setDefaultDistrict("樊城区");
                }
                mPicker.setConfig(cityConfig);
                mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district)
                    {
                        binding.tvCityName.setText(province.getName() + "  " + city.getName() + "  " + district.getName());
                    }
                    @Override
                    public void onCancel()
                    {
                    }
                });
                //显示
                mPicker.showCityPicker();
                */

            }
        });
        /*
        binding.etAddressParticulars.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    hideSoftInput();
                    return true;
                }
                return false;
            }
        });
        */
        // 提交保存或更新地址信息
        binding.btnSave.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                String err = viewModel.checkedErrStr(viewModel.checkedPhone(addressEntity.getPhone()),
                        viewModel.checkedNull(addressEntity.getShipTo(), "收件人"),
                        viewModel.checkedNull(addressEntity.getPhone(), "电话号码"),
                        viewModel.checkedNull(addressEntity.getAddress(), "所在地区"),
                        viewModel.checkedNull(addressEntity.getAddressDetail(), "详细地址"));
                String phoneNumber = addressEntity.getPhone().replaceAll(" ", "");
                addressEntity.setPhone(phoneNumber);
                if (err == null) {
                    if (isUpdate)
                    {
                        //addressEntity.setRegionId(mRegionId);
                        viewModel.editAddress(editAddressId,addressEntity,userKey)
                                 .observe(getActivity(), new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity())
                                 {
                            @Override
                            protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                            {
                                finish();
                            }
                        });
                    } else {

                        addressEntity.setRegionId(mRegionId);
                        addressEntity.setLongitude( addressEntity.getLongitude() );
                        addressEntity.setLatitude( addressEntity.getLatitude() );
                        viewModel.addAddr(addressEntity,userKey)
                                 .observe(getActivity(), new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity())
                                 {
                                    @Override
                                    protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                                    {
                                        if( data.data.isSuccess() )
                                        {
                                            finish();
                                        }
                                        else
                                        {

                                        }

                                    }
                        });
                    }
                }
                else
                {
                    UIUtils.showToastSafesClose(err);
                }
            }
        });

        //加载地址数据

        pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v)
            {
                StringBuffer citySb = new StringBuffer();
                String opt1tx_province = province1Item.size() > 0 ?
                        province1Item.get(options1).getName(): "";
                citySb.append( opt1tx_province );

                String opt2tx_city = city2Item.size() > 0
                        && city2Item.get(options1).size() > 0 ?
                        city2Item.get(options1).get(options2).getName() : "";
                citySb.append( opt2tx_city );
                String opt3tx_district = city2Item.size() > 0
                        && district3Item.get(options1).size() > 0
                        && district3Item.get(options1).get(options2).size() > 0 ?
                        district3Item.get(options1).get(options2).get(options3).getName() : "";
                citySb.append( opt3tx_district );
                addressEntity.setRegionFullName( citySb.toString() );
                //binding.tvCityName.setText(citySb.toString());

                if( city2Item.size() > 0
                        && district3Item.get(options1).size() > 0
                        && district3Item.get(options1).get(options2).size() > 0 )
                {
                    mRegionId =  Integer.parseInt(district3Item.get(options1).get(options2).get(options3).getID());
                }
                else if( city2Item.size() > 0
                        && city2Item.get(options1).size() > 0 )
                {
                    mRegionId =  Integer.parseInt(city2Item.get(options1).get(options2).getID());
                }
                else if(province1Item.size() > 0)
                {
                    mRegionId =  Integer.parseInt(province1Item.get(options1).getID());
                }

                if( mRegionId != 0 )
                {
                    addressEntity.setRegionId( mRegionId );
                }

            }
        }).setTitleText("请选择")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(12)
                .build();

        province1Item = CityDataUtil.getInstance().getProvince1Items();
        city2Item = CityDataUtil.getInstance().getCity2Items();
        district3Item = CityDataUtil.getInstance().getDistrict3Items();

        //三级选择器
        pickerView.setPicker(province1Item, city2Item, district3Item);

        //获取经纬度
        //tlLocationMgr = TencentLocationManager.getInstance(getActivity());
        //搜索 地址 获取 经纬度
        binding.etAddress.setOnClickListener( v -> {
            if( UIUtils.isEmpty( addressEntity.getRegionFullName() ) )
            {
                UIUtils.showToastSafes("请先选择地区");
                return;
            }
            // 先判断
            SearchAddressActivity.start( this ,addressEntity.getRegionFullName());
        } );

        //拿到 返回的 地点 和 经纬度
        LiveEventBus.get(AppConstants.EventKey.POI_SELECT, PoiPlaceBean.class)
                    .observe(this,poiPlaceBean -> {
                        // 获取到 选择的地点
                        LogUtil.e( poiPlaceBean.getTitle() );
                        if( UIUtils.isNotEmpty( poiPlaceBean ) && UIUtils.isNotEmpty( addressEntity ) )
                        {
                            if(   poiPlaceBean.getAddress().contains( addressEntity.getRegionFullName() )   )
                            {
                                String addr = poiPlaceBean.getAddress().replace(addressEntity.getRegionFullName(),"").trim() + poiPlaceBean.getTitle();
                                addressEntity.setAddress( addr );
                            }
                            else
                            {
                                addressEntity.setAddress( poiPlaceBean.getTitle() );
                            }

                            addressEntity.setLatitude( poiPlaceBean.getLat() );
                            addressEntity.setLongitude( poiPlaceBean.getLng() );
                        }
                    });

    }

    @Override
    protected void initData()
    {

    }

    private void queryAddressId(int addrId )
    {
        viewModel.getAddressDetailById(addrId,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<AddressDetailResult>>()
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<AddressDetailResult> data)
                     {
                         setAddressInfo(data.data.getShippingAddress());
                     }

                     @Override
                     public boolean isEmptyData(LiveDataWrapper<AddressDetailResult> data)
                     {
                         return UIUtils.isEmpty( data.data.getShippingAddress() );
                     }
                 });
    }

    private void setAddressInfo(AddressResult.AddressBean addressInfo)
    {
        addressEntity = new AddressNewEntity();

        addressEntity.setRegionId( addressInfo.getRegionId() );
        addressEntity.setShipTo(addressInfo.getShipTo());
        addressEntity.setPhone(addressInfo.getPhone());
        addressEntity.setRegionFullName(addressInfo.getRegionFullName());
        addressEntity.setAddress(addressInfo.getAddress());
        addressEntity.setAddressDetail(addressInfo.getAddressDetail());
        addressEntity.setLatitude(addressInfo.getLatitude());
        addressEntity.setLongitude(addressInfo.getLongitude());

        binding.tvCityName.setText( addressInfo.getRegionFullName() );

        // 这里 隐藏 设置 默认
        if( !addressInfo.isIsDefault() )
        {
            //VISIBLE
            binding.tvDefault.setVisibility(View.INVISIBLE);
        }
        else
        {
            binding.tvDefault.setVisibility(View.GONE);
        }

        binding.setItem(addressEntity );
        binding.executePendingBindings();
    }


    /**
     * 获取单次定位
     *
     */
    private void singleGetLocation()
    {
        /*
        tlLocationMgr.requestSingleFreshLocation(null, new TencentLocationListener() {
            @Override
            public void onLocationChanged(TencentLocation tencentLocation, int i, String s)
            {
                //LogUtil.e("tlLocationMgr","city = " + tencentLocation.getCity() + " District = " + tencentLocation.getDistrict() );
                //LogUtil.e( "s = " + JacksonUtils.transBean2Json( tencentLocation ));
                //Lat = tencentLocation.getLatitude();
                //Lng = tencentLocation.getLongitude();
            }
            @Override
            public void onStatusUpdate(String s, int i, String s1)
            {}
        }, Looper.getMainLooper());
        */
    }

}
